import { Controller } from 'egg';
const Sequelize = require('sequelize');
const cheerio = require('cheerio');
const urlParse = require('url-parse');
const Op = Sequelize.Op;

export default class ContentController extends Controller {
  /**
   * @api {get} article/list/:status 查找特定类型的文章列表(前台)
   *  
   * @apiName specificType
   * @apiGroup Articles
   * @apiDescription 查找特定类型的文章列表 允许status: random(随机) lastest(最新)
   * @apiParam {Boolean} [onlyOne] 是否只有一页的内容,默认为false 
   * @apiParam {Number} [pageNo] 页码
   * @apiParam {Number} [pageSize] 页数
   */
  public async specificArticle(ctx) {
    let { status } = ctx.params;
    let { onlyOne = false, pageNo = 1, pageSize = 10 } = ctx.request.query;
    if (onlyOne) {
      pageNo = 1;
    }
    const { limit, offset } = ctx.helper.changePage(pageNo, pageSize);
    let list;
    if (status === 'lastest') {
      list = await ctx.model.Article.findAll({
        attributes: {
          exclude: ['id', 'downLinks', 'status', 'updatedAt'],
        },
        order: [
          ['createdAt', 'DESC'],
        ],
        where: {
          status: 'publish'
        },
        limit: limit,
        offset: offset
      });
    } else if (status === 'random') {
      /* let count = await ctx.model.Article.findAll({
        attributes: {
          exclude: ['id', 'downLinks', 'status', 'createdAt', 'updatedAt'],
        },
        order: Sequelize.random(),
        limit: limit,
        offset: offset
      });
      console.log(count); */
    }
    ctx.response.body = {
      code: 200,
      data: list,
      status: '成功'
    };
  }

  /**
   * @api {get} article/detail/:articleId 查找文章内容详情(前台)
   *  
   * @apiName detailMessage
   * @apiGroup Articles
   * @apiDescription 查找特定的文章内容
   */
  public async articleDetail(ctx) {
    let { articleId } = ctx.params;
    let data = await ctx.model.Article.findOne({
      attributes: {
        exclude: ['id', 'status', 'updatedAt', 'toTop'],
      },
      where: {
        articleId: parseInt(articleId),
        status: 'publish'
      }
    });
    if (data) {
      ctx.response.body = {
        code: 200,
        data: data,
        status: '成功'
      }
    } else {
      ctx.response.body = ctx.helper.getErrorMsg(225);
    }
  }

  /**
   * @api {get} article/list 获取文章列表数据(后台)
   *  
   * @apiName article_list
   * @apiGroup Articles
   * @apiDescription 获取文章列表数据
   * @apiParam {ArrayString} [articleIds] 文章ids
   * @apiParam {String} [status] 文章状态
   * @apiParam {Number} [pageNo] 页码
   * @apiParam {Number} [pageSize] 页数
   */
  public async articleList(ctx) {
    let { articleIds, status, pageNo = 1, pageSize = 10 } = ctx.request.query;
    let pageObject = this.ctx.helper.changePage(pageNo, pageSize);
    let searchObject = {};
    if (status) {
      searchObject = Object.assign(searchObject, {
        status: status
      })
    }
    if (articleIds) {
      let tempArticleIdsArray = articleIds.split(',');
      tempArticleIdsArray = tempArticleIdsArray.map(id => {
        return parseInt(id);
      })
      searchObject = Object.assign(searchObject, {
        articleIds: {
          [Op.or]: tempArticleIdsArray
        }
      });
    }
    let data = await ctx.model.Article.findAndCountAll({
      where: searchObject,
      limit: pageObject.limit,
      offset: pageObject.offset
    });

    data.rows.forEach(item => {
      item.dataValues.downLinks = JSON.parse(JSON.parse(item.dataValues.downLinks));
    });
    this.ctx.response.body = {
      code: 200,
      data: data.rows,
      count: data.count,
      status: '成功'
    }
  }

  /**
   * @api {post} article/add 文章添加(后台)
   *  
   * @apiName article_add
   * @apiGroup Articles
   * @apiDescription 文章添加  status:publish-发布 unPublish-未发布 ,downlinks 必须为对象字符串用于解析出所有的Link地址
   * @apiParam {String} title 标题
   * @apiParam {String} summary 简介摘要
   * @apiParam {String} content 主内容
   * @apiParam {Boolean} toTop 是否置顶
   * @apiParam {Boolean} download 是否可以下载
   * @apiParam {String} preview 预览图
   * @apiParam {Integer} categoryId 分类
   * @apiParam {Integer} subCategoryId 二级分类
   * @apiParam {Array} downlinks 下载链接,格式:"{name:'',url:''}"
   * @apiParam {String} tags 标签
   */
  public async articleAdd() {
    let {
      title,
      summary,
      content,
      categoryId,
      subCategoryId,
      status,
      preview = '',
      tags,
      toTop,
      download,
      autoImage,
      autoSummary,
      downlinks }
      = this.ctx.request.body;
    let articles = await this.ctx.model.Article.findAll();
    let mapArray = articles.map(item => {
      return parseInt(item.articleId);
    });

    let downLinksString = JSON.stringify(downlinks);
    let maxValue: any = Math.max.apply(Math, mapArray.length === 0 ? [0] : mapArray);
    if (autoImage) {
      const $ = cheerio.load(content);
      let srcObject = $('img').attr('src');
      const src = srcObject.length ? srcObject : '';
      const url = new urlParse(src);
      const pathname = url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname;
      preview = pathname;
    }
    await this.ctx.model.Article.create({
      title,
      author: 'admin',
      status: status || 'publish',
      summary,
      content,
      autoImage,
      autoSummary,
      toTop,
      download,
      articleId: parseInt(maxValue) + 1,
      categoryId: parseInt(categoryId),
      subCategoryId: parseInt(subCategoryId),
      preview,
      tags,
      downLinks: downLinksString
    });
    this.ctx.response.body = {
      code: 200,
      status: '添加成功'
    }
  }

  /**
   * @api {post} article/update/articleId 文章编辑(后台)
   *  
   * @apiName article_update
   * @apiGroup Articles
   * @apiDescription 文章编辑  status:publish-发布 unPublish-未发布,downlinks 必须为对象字符串用于解析出所有的Link地址
   * @apiParam {String} title 标题
   * @apiParam {String} summary 简介摘要
   * @apiParam {String} content 主内容
   * @apiParam {Boolean} toTop 是否置顶
   * @apiParam {Boolean} download 是否可以下载
   * @apiParam {String} preview 预览图
   * @apiParam {Integer} categoryId 一级分类
   * @apiParam {Integer} subCategoryId 二级分类
   * @apiParam {Array} downlinks 下载链接,格式:"{name:'',url:''}"
   * @apiParam {String} tags 标签
   */
  public async aritcleUpdate() {
    try {
      let { articleId } = this.ctx.params;

      if (!articleId) {
        throw this.ctx.helper.getErrorMsg(207);
      }
      let body = this.ctx.request.body;
      body.downLinks = JSON.stringify(body.downlinks);
      if (body.autoImage) {
        const $ = cheerio.load(body.content);
        let srcObject = $('img').attr('src');
        const src = srcObject.length ? srcObject : '';
        const url = new urlParse(src);
        const pathname = url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname;
        body.preview = pathname;
      }

      await this.ctx.model.Article.update(
        body,
        {
          where: {
            articleId: parseInt(articleId)
          }
        });
      this.ctx.response.body = {
        code: 200,
        status: '成功'
      }
    } catch (err_info) {
      this.ctx.response.body = err_info;
    }
  }

  /**
   * @api {get} article/delete/:articleId? 文章删除(后台)
   *  
   * @apiName article_delete
   * @apiGroup Articles
   * @apiDescription 文章删除
   */

  public async articleDelte() {
    try {
      let { articleId } = this.ctx.params;
      if (!articleId) {
        throw this.ctx.helper.getErrorMsg(207);
      }
      await this.ctx.model.Article.destroy({
        where: {
          articleId: articleId
        }
      });
      this.ctx.response.body = {
        code: 200,
        status: '成功'
      };
    } catch (err_info) {
      this.ctx.response.body = err_info;
    }
  }

  /**
   * @api {get} article/delPreview/:articleId? 删除文章预览图(后台)
   *  
   * @apiName delPreview
   * @apiGroup Articles
   */
  async articleDelPreview(ctx) {
    let { articleId } = ctx.params;
    try {
      if (!articleId) {
        throw ctx.helper.getErrorMsg(207);
      }
      await ctx.model.Article.update({
        preview: ''
      }, {
        where: {
          articleId: parseInt(articleId)
        }
      });
      ctx.response.body = {
        code: 200,
        status: '删除成功'
      };

    } catch (err_info) {
      ctx.response.body = err_info;
    }

  }

  /**
   * @api {post} article/status/:articleId? 修改文章状态(后台)
   *  
   * @apiName article_status
   * @apiGroup Articles
   * @apiDescription 文章状态修改  status:publish-发布 unPublish-未发布
   * @apiParam {String} status 修改之后的文章状态
   */
  async articleStatus() {
    let { articleId } = this.ctx.params;
    let { status } = this.ctx.request.body;
    try {
      if (!articleId || !status) {
        throw this.ctx.helper.getErrorMsg(207);
      }
      await this.ctx.model.Article.update({
        status: status
      },
        {
          where: {
            articleId: parseInt(articleId)
          }
        });
      this.ctx.response.body = {
        code: 200,
        status: '成功'
      };
    } catch (err) {
      this.ctx.response.body = err;
    }

  }
}
